//
//  OrderViewController.m
//  Gourmet
//
//  Created by WardenAllen on 15/12/22.
//  Copyright © 2015年 王东. All rights reserved.
//

#import "OrderViewController.h"
#import "CartButton.h"
#import "DishInfoView.h"
#import "OrderInfo.h"
#import "AppDelegate.h"
#import "CartTableViewController.h"

#define ADD_TO_CART_BTN_HEIGHT 48

@interface OrderViewController () <UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *orderScrollView;
@property (nonatomic, assign) NSInteger dishCount;
@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, strong) UILabel *currentPageLabel;
@property (nonatomic, strong) UILabel *totalLabel;

@property (nonatomic, strong) NSMutableArray *imageViewArray;
@property (nonatomic, strong) CartButton *cartBtn;
@property (nonatomic, strong) DishInfoView *dishInfoView;

@property (nonatomic, strong) AppDelegate *myAppDelegate;

@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _myAppDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    self.title = [self.restaurantInfo objectForKey:@"RestaurantName"];
    
    self.cartBtn = [[CartButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24) badgeNumber:0];
    [self.cartBtn setImage:[UIImage imageNamed:@"购物袋.png"] forState:UIControlStateNormal];
    [self.cartBtn addTarget:self action:@selector(cartBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.cartBtn];
    
    //测试数量
    self.dishCount = 10;
    
    self.orderScrollView = [UIScrollView new];
    self.orderScrollView.frame = CGRectMake(0, 60, kWIDTH, kHEIGHT-60);
    self.orderScrollView.delegate = self;
    self.orderScrollView.contentSize = CGSizeMake(kWIDTH*self.dishCount, 0);
    self.orderScrollView.backgroundColor = [UIColor colorWithRed:0.0 green:0 blue:0 alpha:0.0];
    self.orderScrollView.pagingEnabled = YES;
    self.orderScrollView.showsVerticalScrollIndicator = NO;
    self.orderScrollView.bounces = NO;
    
    [self.view addSubview:self.orderScrollView];
    
    self.currentPage = 1;
    self.currentPageLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWIDTH-70, kHEIGHT-50, 30, 30)];
    self.currentPageLabel.textAlignment = NSTextAlignmentRight;
    self.currentPageLabel.textColor = [UIColor blackColor];
    self.currentPageLabel.text = [NSString stringWithFormat:@"%ld", (long)self.currentPage];
    
    self.totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWIDTH-40, kHEIGHT-50, 40, 30)];
    self.totalLabel.textAlignment = NSTextAlignmentLeft;
    self.totalLabel.textColor = [UIColor blackColor];
    self.totalLabel.text = [NSString stringWithFormat:@"/%ld", (long)self.dishCount];
    
    self.imageViewArray = [NSMutableArray array];

#warning 占用大量内存
    
    for (int i=0; i<self.dishCount; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(kWIDTH*i, 0, kWIDTH, kWIDTH*3/4)];
        [self.imageViewArray addObject:imageView];
        [self.orderScrollView addSubview:imageView];
    }
    
    [self.view insertSubview:self.currentPageLabel aboveSubview:self.orderScrollView];
    [self.view insertSubview:self.totalLabel aboveSubview:self.orderScrollView];
    
    AVQuery *query = [AVQuery queryWithClassName:@"RestaurantImages"];
    //[query whereKey:@"restaurantId" equalTo:@1];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 检索成功
            NSLog(@"Successfully retrieved %lu posts.", (unsigned long)objects.count);
            for (int i=0; i<objects.count; i++) {
                AVObject *restaurantInfo = objects[i];
                AVFile *file = [restaurantInfo objectForKey:@"restaurantImage"];
                [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                    if (!error) {
                        if (self.imageViewArray.count >= i+1) {
                            UIImageView *imageView = self.imageViewArray[i];
                            imageView.image = [UIImage imageWithData:data];
                        }
                    } else {
                        NSLog(@"%@ %@", error, [error userInfo]);
                    }
                }];
            }
        } else {
            // 输出错误信息
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];
    
    self.dishInfoView = [[DishInfoView alloc] initWithFrame:CGRectMake(0, kWIDTH*3/4+60, kWIDTH, kHEIGHT-kWIDTH*3/4-ADD_TO_CART_BTN_HEIGHT*kWIDTH_RATIO)];
    [self.view insertSubview:self.dishInfoView belowSubview:self.orderScrollView];
    
    //移除出购物车按钮
    UIButton *removeFromCartBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kHEIGHT-ADD_TO_CART_BTN_HEIGHT*kWIDTH_RATIO, kWIDTH/2-0.5, ADD_TO_CART_BTN_HEIGHT*kWIDTH_RATIO)];
    removeFromCartBtn.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.6];
    [removeFromCartBtn addTarget:self action:@selector(removeFromCartBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [removeFromCartBtn setTitle:@"-" forState:UIControlStateNormal];
    [removeFromCartBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view insertSubview:removeFromCartBtn aboveSubview:self.orderScrollView];
    //添加到购物车按钮
    UIButton *addToCartBtn = [[UIButton alloc] initWithFrame:CGRectMake(kWIDTH/2+0.5, kHEIGHT-ADD_TO_CART_BTN_HEIGHT*kWIDTH_RATIO, kWIDTH/2-0.5, ADD_TO_CART_BTN_HEIGHT*kWIDTH_RATIO)];
    addToCartBtn.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.6];
    [addToCartBtn addTarget:self action:@selector(addToCartBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [addToCartBtn setTitle:@"+" forState:UIControlStateNormal];
    [addToCartBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view insertSubview:addToCartBtn aboveSubview:self.orderScrollView];
    
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.currentPageLabel.text = [NSString stringWithFormat:@"%d", (int)(scrollView.contentOffset.x/kWIDTH+0.5)+1];
    //self.cartBtn.badgeNumber = (int)(scrollView.contentOffset.x/kWIDTH+0.5)+1;
    
    NSString *imageName = [NSString stringWithFormat:@"chef%d.png", ((int)(scrollView.contentOffset.x/kWIDTH+0.5)+1)%5+1];
    self.dishInfoView.chefHeafImage = [UIImage imageNamed:imageName];
}

#pragma mark - Actions

- (void)cartBtnClicked:(id)sender {
    
    //测试
    OrderInfo *orderInfo = (OrderInfo *)[NSEntityDescription insertNewObjectForEntityForName:@"OrderInfo" inManagedObjectContext:self.myAppDelegate.managedObjectContext];
    [orderInfo setOrderId:@1];
    [orderInfo setUserId:@10];
    [orderInfo setRestaurantId:[NSNumber numberWithInteger:[[self.restaurantInfo objectForKey:@"RestaurantId"] integerValue]]];
    [orderInfo setRestaurantName:[self.restaurantInfo objectForKey:@"RestaurantName"]];
    [orderInfo setOrderTime:[NSDate date]];
    [orderInfo setOrderState:@1];
    [orderInfo setCouponType:@2];
    [orderInfo setOrderTotalPrice:@100.3];
    [orderInfo setOrderOffPrice:@20];
    [orderInfo setOrderRealPrice:@80.3];
    [orderInfo setPaymentType:@1];
    [orderInfo setOrderRemark:@"不要辣椒"];
    
    NSMutableArray *orderArray = [NSMutableArray array];
    for (int i=0; i<11; i++) {
        NSDictionary *orderDic = [[NSDictionary alloc]
                                  initWithObjects:@[[NSString stringWithFormat:@"菜名 %d", i],
                                                    [NSString stringWithFormat:@"%d", i+1],
                                                    [NSString stringWithFormat:@"%f", (i+1)*10.0]]
                                  forKeys:@[@"DishName", @"DishCount", @"DishPrice"]];
        [orderArray addObject:orderDic];
    }
    [orderInfo setOrderContent:[NSKeyedArchiver archivedDataWithRootObject:orderArray]];
    
    CartTableViewController *ctvc = (CartTableViewController *)[[AppDelegate globalDelegate] CartTableViewController];
    ctvc.orderInfo = orderInfo;
    [self.navigationController pushViewController:ctvc animated:YES];
}

- (void)addToCartBtnClicked:(id)sender {
    self.cartBtn.badgeNumber += 1;
}

- (void)removeFromCartBtnClicked:(id)sender {
    if (self.cartBtn <= 0) {
        self.cartBtn.badgeNumber = 0;
    } else {
        self.cartBtn.badgeNumber -= 1;
    }
}

@end
